package com.example.bingobox.ui.home;

import android.app.Application;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.example.bingobox.model.Task;
import com.example.bingobox.model.TodoBox;
import com.example.bingobox.model.TodoBoxData;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class HomeViewModel extends AndroidViewModel {
    private static final String TAG = "HomeViewModel";
    private final MutableLiveData<Task> currentTask = new MutableLiveData<>();
    private List<Task> allTasks;
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    private final Random random = new Random();

    public HomeViewModel(@NonNull Application application) {
        super(application);
        loadTasks();
        drawRandomTask();
    }

    private void loadTasks() {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");
            
            if (!todoboxFile.exists()) {
                allTasks = new ArrayList<>();
                return;
            }
            
            String json = new String(Files.readAllBytes(todoboxFile.toPath()));
            
            TodoBoxData data = gson.fromJson(json, TodoBoxData.class);
            
            if (data == null) {
                allTasks = new ArrayList<>();
                return;
            }
            
            if (data.getTasks() == null) {
                allTasks = new ArrayList<>();
                return;
            }
 
            // 过滤掉已完成和已过期的任务
            allTasks = new ArrayList<>();
            long currentTime = System.currentTimeMillis();
            for (Task task : data.getTasks()) {
                if (task != null && !task.isCompleted() && 
                    (task.getDeadline() == 0 || task.getDeadline() > currentTime)) {
                    allTasks.add(task);
                }
            }
        } catch (Exception e) {
            allTasks = new ArrayList<>();
        }
    }

    public LiveData<Task> getCurrentTask() {
        return currentTask;
    }

    public void drawRandomTask() {
        // 重新加载任务数据
        loadTasks();
        
        if (allTasks != null && !allTasks.isEmpty()) {
            int idx = random.nextInt(allTasks.size());
            Task task = allTasks.get(idx);
            currentTask.setValue(task);
        } else {
            currentTask.setValue(null);
        }
    }
}